	package com.jec;

import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.Properties;

import com.google.common.base.StandardSystemProperty;

import lombok.Getter;
import lombok.extern.log4j.Log4j;

@Log4j
public class Bootstrap {
	
	@Getter
	private static boolean needInitializeDatabase = false;
	
	private static Properties systemProperties = null;
	
	public static Properties bootstrap() {
		
		// load application config
		Properties sys = getApplicationProperties();
		
		// config for spring
		Properties properties = new Properties();

		// override
		//properties.setProperty("spring.datasource.url", "jdbc:h2:file:./tcs_db/data;AUTO_SERVER=TRUE;DB_CLOSE_DELAY=-1");
		String url = "jdbc:h2:file:" + getApplicationPath() + File.separatorChar + "tcs_db" + File.separatorChar + "data";
		properties.setProperty("spring.datasource.url", sys.getProperty("db.url", url));
		properties.setProperty("spring.datasource.driver-class", sys.getProperty("db.driver", "org.h2.Driver"));
		properties.setProperty("spring.datasource.username", sys.getProperty("db.username", "sa"));
		properties.setProperty("spring.datasource.password", sys.getProperty("db.password", "sa"));	
		
		// fixed 
		properties.setProperty("debug", "false");	
		
		//properties.setProperty("spring.aop.auto", "false");
		//properties.setProperty("spring.aop.proxy-target-class", "true");
		//properties.setProperty("spring.jpa.properties.hibernate.current_session_context_class", "org.springframework.orm.hibernate4.SpringSessionContext");	
		//properties.setProperty("spring.jpa.properties.hibernate.current_session_context_class", "jta");	
		properties.setProperty("spring.jpa.properties.hibernate.hbm2ddl.auto", "update");	
		properties.setProperty("spring.jpa.properties.hibernate.dialect", "org.hibernate.dialect.MySQLDialect");	
		properties.setProperty("spring.jpa.properties.hibernate.format_sql", "true");	
		properties.setProperty("spring.jpa.properties.hibernate.show_sql", "false");
		
		//properties.setProperty("spring.mvc.static-path-pattern","/rest/**");
		properties.setProperty("spring.resources.static-locations", 
				"classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/static/static/");
		
		log.info("Building spring properties...");
		log.info("Database url: " + properties.getProperty("spring.datasource.url"));
		
		/*
		 * 检查数据库
		 * 如果数据库没有初始化，采用update模式，自动创建表格，同时由DatabaseStart负责初始化视图；
		 * 否则，采用none模式，不需要初始化数据库
		 */
		{
			try {
				Class.forName(properties.getProperty("spring.datasource.driver-class"));
				Connection conn = DriverManager.getConnection(
						properties.getProperty("spring.datasource.url"), 
						properties.getProperty("spring.datasource.username"), 
						properties.getProperty("spring.datasource.password"));
				
				DatabaseMetaData meta = conn.getMetaData();
				
				boolean found = false;
				
				if(!found) {
					ResultSet rs = meta.getTables(null, null, "ZHWG_LOG_OPERATE", null);
					if(rs.next()) {
						found = true;
					}
				}
				
				if(!found) {
					ResultSet rs = meta.getTables(null, null, "zhwg_log_operate", null);
					if(rs.next()) {
						found = true;
					}
				}
				
				
				if(found) {
					properties.setProperty("spring.jpa.properties.hibernate.hbm2ddl.auto", "none");
					log.info("Database is ready, hbm2ddl.auto=none");
				} else {
					properties.setProperty("spring.jpa.properties.hibernate.hbm2ddl.auto", "update");
					needInitializeDatabase = true;
					log.info("Database is ready, hbm2ddl.auto=update");
				}
				
				
				
			} catch (Exception e) {
				
				log.error("Checking database failed.", e);
				
				System.exit(0);
				
			}
			
			
		}
		
		return properties;
		
		
	}
	
	
	public static String getApplicationPath() {
		
		String home = StandardSystemProperty.USER_HOME.value();
		
		String path = home + File.separatorChar + ".tcs";
		
		File p = new File(path);
		
		if(p.isFile())
			p.delete();
		
		if(!p.exists()) 
			p.mkdirs();
		
		return path;
		
	}
	
	public static File getConfigFile() {
		
		String path = getApplicationPath();
		
		String filename = path + File.separatorChar + "tcs.properties";
		
		File configFile = new File(filename);
		
		return configFile;
	}
	
	public static void reset() {
		systemProperties = null;
	}
	
	public static Properties getApplicationProperties() {
		
		if(systemProperties == null) {
				
			File configFile = getConfigFile();
			
			System.out.println("Loading: " + configFile.getAbsolutePath());
			
			Properties properties = new Properties();
			
			if(configFile.exists() && configFile.isFile()) {
				try {
					properties.load(new FileInputStream(configFile));
				} catch(Exception e) {
					e.printStackTrace();
				}
			}
			
			systemProperties = properties;
		}
		
		return systemProperties;
		
	}

}
